package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-08-31
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictListener dictListener;

    //根据数据id查询子数据列表
    @Cacheable(value = "dict", key = "'selectIndexList'+#id")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for (Dict dict : dicts) {
            Long dictId = dict.getId();
          boolean isChild =  this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }

        return dicts;
    }
    //导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查数据库的数据 返回到前端
            List<DictEeVo> dictEeVoList =new ArrayList();
            List<Dict> dictList = baseMapper.selectList(null);
            for (Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictVo);
                dictEeVoList.add(dictVo);
            }
            //调方法导出
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //导入
    @Override
    public void importData(MultipartFile file) {
       try {
           EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
       }catch (Exception e){
           e.printStackTrace();
       }
    }
    //根据编号查询对应和名称
    @Override
    public String getNameByDictCodevalue(String dictCode, String value) {
        //根据value 查询
        //如果dictCode空 直接根据value 查询
        if (StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> wrapperValue =new QueryWrapper<>();
            wrapperValue.eq("value", value);

            Dict dict = baseMapper.selectOne(wrapperValue);
            if (dict!=null){
                return dict.getName();
            }
        }else {
            //根据dictCode查询
            QueryWrapper<Dict> wrapper =new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);
            Dict dictParent = baseMapper.selectOne(wrapper);
            System.out.println("dictParent = " + dictParent);
            //2.取parentId，在加value 条件查
            QueryWrapper<Dict> wrapperChild =new QueryWrapper<>();
            wrapperChild.eq("parent_id",dictParent.getId());
            wrapperChild.eq("value", value);
            Dict dictChild = baseMapper.selectOne(wrapperChild);
            if (dictChild!=null){
                return dictChild.getName();
            }
        }
        return null;
    }

    @Override
    public List<Dict> findDictCodeByAll(String dictCode) {
      //根据dictcode查询
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dictParent = baseMapper.selectOne(wrapper);
        if (dictParent==null){
            return null;
        }

        //获取id值 查下面的省份
        Long parentId = dictParent.getId();
        List<Dict> dictList = this.findChildData(parentId);
        return dictList;
    }

    //判断是否还有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
